package com.plumecache.core;

import com.plumecache.core.exception.PlumeCacheException;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.redisnode.RedisNode;
import org.redisson.api.redisnode.RedisNodes;
import org.redisson.api.redisnode.RedisSingle;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

import java.util.Map;

public class SingleRedisCacheService extends RedisCacheService {

    @Override
    public void initialize(InstanceProperties properties) {
        super.initialize(properties);

        String endpoint = properties.getEndpoint();
        if (StringUtils.isEmpty(endpoint)) {
            throw new PlumeCacheException("can't find [endpoint] properties");
        }

        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress("redis://".concat(endpoint));

        if (StringUtils.isNotBlank(properties.getUsername())) {
            singleServerConfig.setUsername(properties.getUsername());
        }

        if (StringUtils.isNotBlank(properties.getPassword())) {
            singleServerConfig.setPassword(properties.getPassword());
        }

        if (StringUtils.isNotBlank(properties.getTimeout())) {
            singleServerConfig.setTimeout(Integer.parseInt(properties.getTimeout()));
        }

        if (StringUtils.isNotBlank(properties.getConnectTimeout())) {
            singleServerConfig.setConnectTimeout(Integer.parseInt(properties.getConnectTimeout()));
        }

        if (StringUtils.isNotBlank(properties.getConnectionPoolSize())) {
            singleServerConfig.setConnectionPoolSize(Integer.parseInt(properties.getConnectionPoolSize()));
        }

        redissonClient = Redisson.create(config);
    }

    @SneakyThrows
    @Override
    public Map<String, String> getStatistics() {
        RedisSingle redisNodes = redissonClient.getRedisNodes(RedisNodes.SINGLE);
        return redisNodes.getInstance().info(RedisNode.InfoSection.ALL);
    }
}
